package studentdemo.ui;

import studentdemo.modul.Student;
import studentdemo.server.StudentService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.util.List;

public class StudentPanel extends JPanel {
    private StudentService studentService = new StudentService();
    private JTable table;
    private DefaultTableModel tableModel;
    private JTextField searchIdField, searchNameField;
    private JButton searchBtn, addBtn, editBtn, deleteBtn, prevBtn, nextBtn, refreshBtn;
    private int currentPage = 1;
    private final int pageSize = 10;
    private int totalPage = 1;

    public StudentPanel() {
        setLayout(new BorderLayout());
        // 顶部查询区
        JPanel searchPanel = new JPanel();
        searchPanel.add(new JLabel("学号:"));
        searchIdField = new JTextField(8);
        searchPanel.add(searchIdField);
        searchPanel.add(new JLabel("姓名:"));
        searchNameField = new JTextField(8);
        searchPanel.add(searchNameField);
        searchBtn = new JButton("查询");
        searchPanel.add(searchBtn);
        refreshBtn = new JButton("刷新");
        searchPanel.add(refreshBtn);
        add(searchPanel, BorderLayout.NORTH);

        // 表格区
        String[] columns = {"学号", "姓名", "性别", "年龄", "地区", "已修学分", "班级编号"};
        tableModel = new DefaultTableModel(columns, 0) {
            public boolean isCellEditable(int row, int column) { return false; }
        };
        table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        // 底部操作区
        JPanel opPanel = new JPanel();
        addBtn = new JButton("新增");
        editBtn = new JButton("修改");
        deleteBtn = new JButton("删除");
        prevBtn = new JButton("上一页");
        nextBtn = new JButton("下一页");
        opPanel.add(addBtn);
        opPanel.add(editBtn);
        opPanel.add(deleteBtn);
        opPanel.add(prevBtn);
        opPanel.add(nextBtn);
        add(opPanel, BorderLayout.SOUTH);

        // 事件绑定
        searchBtn.addActionListener(e -> searchAction());
        refreshBtn.addActionListener(e -> loadTable(currentPage));
        addBtn.addActionListener(e -> showStudentDialog(null));
        editBtn.addActionListener(e -> editStudentAction());
        deleteBtn.addActionListener(e -> deleteStudentAction());
        prevBtn.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                loadTable(currentPage);
            }
        });
        nextBtn.addActionListener(e -> {
            if (currentPage < totalPage) {
                currentPage++;
                loadTable(currentPage);
            }
        });

        loadTable(1);
    }

    private void loadTable(int page) {
        tableModel.setRowCount(0);
        int count = studentService.getStudentCount();
        totalPage = (int) Math.ceil(count * 1.0 / pageSize);
        if (totalPage == 0) totalPage = 1;
        List<Student> list = studentService.getStudentsByPage(page, pageSize);
        for (Student s : list) {
            tableModel.addRow(new Object[]{
                    s.getSno(), s.getSname(), s.getSsex(), s.getSage(), s.getSrname(), s.getStotalcredit(), s.getSclno()
            });
        }
    }

    private void searchAction() {
        String sno = searchIdField.getText().trim();
        String name = searchNameField.getText().trim();
        tableModel.setRowCount(0);
        if (!sno.isEmpty()) {
            Student s = studentService.getStudentById(sno);
            if (s != null) {
                tableModel.addRow(new Object[]{
                        s.getSno(), s.getSname(), s.getSsex(), s.getSage(), s.getSrname(), s.getStotalcredit(), s.getSclno()
                });
            } else {
                JOptionPane.showMessageDialog(this, "未找到该学号学生");
            }
        } else if (!name.isEmpty()) {
            List<Student> list = studentService.getStudentsByName(name);
            for (Student s : list) {
                tableModel.addRow(new Object[]{
                        s.getSno(), s.getSname(), s.getSsex(), s.getSage(), s.getSrname(), s.getStotalcredit(), s.getSclno()
                });
            }
        } else {
            loadTable(1);
        }
    }

    private void showStudentDialog(Student student) {
        JTextField snoField = new JTextField();
        JTextField snameField = new JTextField();
        JComboBox<String> ssexBox = new JComboBox<>(new String[]{"男", "女"});
        JTextField sageField = new JTextField();
        JTextField srnameField = new JTextField();
        JTextField stotalcreditField = new JTextField();
        JTextField sclnoField = new JTextField();

        if (student != null) {
            snoField.setText(student.getSno());
            snoField.setEditable(false);
            snameField.setText(student.getSname());
            ssexBox.setSelectedItem(student.getSsex());
            sageField.setText(String.valueOf(student.getSage()));
            srnameField.setText(student.getSrname());
            stotalcreditField.setText(String.valueOf(student.getStotalcredit()));
            sclnoField.setText(student.getSclno());
        }

        JPanel panel = new JPanel(new GridLayout(0, 2));
        panel.add(new JLabel("学号:")); panel.add(snoField);
        panel.add(new JLabel("姓名:")); panel.add(snameField);
        panel.add(new JLabel("性别:")); panel.add(ssexBox);
        panel.add(new JLabel("年龄:")); panel.add(sageField);
        panel.add(new JLabel("地区:")); panel.add(srnameField);
        panel.add(new JLabel("已修学分:")); panel.add(stotalcreditField);
        panel.add(new JLabel("班级编号:")); panel.add(sclnoField);

        int result = JOptionPane.showConfirmDialog(this, panel, student == null ? "新增学生" : "修改学生", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            try {
                String sno = snoField.getText().trim();
                String sname = snameField.getText().trim();
                String ssex = (String) ssexBox.getSelectedItem();
                int sage = Integer.parseInt(sageField.getText().trim());
                String srname = srnameField.getText().trim();
                int stotalcredit = Integer.parseInt(stotalcreditField.getText().trim());
                String sclno = sclnoField.getText().trim();
                Student s = new Student(sno, sname, ssex, sage, srname, stotalcredit, sclno);
                boolean success;
                if (student == null) {
                    success = studentService.addStudent(s);
                } else {
                    success = studentService.updateStudent(s);
                }
                if (success) {
                    JOptionPane.showMessageDialog(this, "操作成功");
                    loadTable(currentPage);
                } else {
                    JOptionPane.showMessageDialog(this, "操作失败");
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "输入有误: " + ex.getMessage());
            }
        }
    }

    private void editStudentAction() {
        int row = table.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "请先选中一行");
            return;
        }
        String sno = (String) tableModel.getValueAt(row, 0);
        Student s = studentService.getStudentById(sno);
        if (s != null) {
            showStudentDialog(s);
        }
    }

    private void deleteStudentAction() {
        int row = table.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, "请先选中一行");
            return;
        }
        String sno = (String) tableModel.getValueAt(row, 0);
        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除学号为" + sno + "的学生吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            boolean success = studentService.deleteStudent(sno);
            if (success) {
                JOptionPane.showMessageDialog(this, "删除成功");
                loadTable(currentPage);
            } else {
                JOptionPane.showMessageDialog(this, "删除失败");
            }
        }
    }
} 